﻿/*
 * @author: wizardc
 */

using Dou.Utils;

namespace Dou.Event
{
    /// <summary>
    /// 事件扩展方法
    /// </summary>
    public static class EventExtends
    {
        public static bool DispatchEvent(this EventDispatcher dispatcher, string type, object data = null, bool cancelable = false)
        {
            DEvent evt = Recyclable.Get<DEvent>();
            evt.InitEvent(type, data, cancelable);
            bool result = dispatcher.Dispatch(evt);
            Recyclable.Recycle(evt);
            return result;
        }
    }

    /// <summary>
    /// 事件类
    /// </summary>
    public class DEvent : ICacheable
    {
        private string _type;
        private object _data;
        private bool _cancelable;
        private bool _isDefaultPrevented = false;

        private IEventDispatcher _target;

        public string type
        {
            get { return _type; }
        }

        public object data
        {
            get { return _data; }
        }

        public bool cancelable
        {
            get { return _cancelable; }
        }

        public IEventDispatcher target
        {
            get { return _target; }
        }

        public DEvent()
        {
        }

        public DEvent(string type = null, object data = null, bool cancelable = false)
        {
            InitEvent(type, data, cancelable);
        }

        public void InitEvent(string type, object data, bool cancelable)
        {
            _type = type;
            _data = data;
            _cancelable = cancelable;
        }

        public void SetTarget(IEventDispatcher target)
        {
            _target = target;
        }

        public void PreventDefault()
        {
            if (_cancelable)
            {
                _isDefaultPrevented = true;
            }
        }

        public bool IsDefaultPrevented()
        {
            return _isDefaultPrevented;
        }

        public void OnRecycle()
        {
            _type = null;
            _data = null;
            _cancelable = false;
            _isDefaultPrevented = false;
            _target = null;
        }

        public void OnReuse()
        {
        }
    }
}
